package com.qf.shop.car.interceptor;

import com.qf.shop.common.constants.AuthConstants;
import com.qf.shop.common.constants.CarConstants;
import com.qf.shop.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 判断用户是否登录，如果登录了就设置UID,没有登录就设置UUID
 */
@Component
@Slf4j
public class UserCarInterceptor implements HandlerInterceptor {
    private ThreadLocal<String> userCarIdThreadlocal = new ThreadLocal<>();

    public String get() {
        // 取值
        return userCarIdThreadlocal.get();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserVo userVo = (UserVo) request.getSession().getAttribute(AuthConstants.LOGIN_USER);
        String userCarId = null;
        log.debug("url:{}",request.getRequestURI());
        log.debug("userVO:{}", userVo);
        if (userVo != null) {
            // 用户登录了
            userCarId = userVo.getId();
            log.debug("用户已经登录:{}", userCarId);
        } else {
            log.debug("用户没有登录");
            // 判断匿名用户名(没有登录)是否有UUID
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (CarConstants.CAR_ANON_NAME.equals(name)) {
                        userCarId = cookie.getValue();
                        break;
                    }
                }
            }
            if (userCarId == null) {
                // 生成一个新的UUID
                userCarId = UUID.randomUUID().toString();
                // 存到Cookie中
                Cookie cookie = new Cookie(CarConstants.CAR_ANON_NAME, userCarId);
                cookie.setMaxAge(60 * 60 * 24 * 7); // 7天
                cookie.setPath("/"); //

                // 把cookie写入到responce中
                response.addCookie(cookie);
            }
        }
        // 放到ThreadLocal中
        userCarIdThreadlocal.set(userCarId);
        return true;
    }
}
